package com.csc.contact.checkbill.task;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.text.DateFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.concurrent.Executors;
import java.util.concurrent.ScheduledExecutorService;
import java.util.concurrent.TimeUnit;

/**
 * 定时任务，获取营销数据插入相应表中
 *
 * @author zhanglei
 * @create 2017-04-18 21:21
 * @email zhanglei@hollycrm.com
 **/
public class MyTask {
    private static final Logger LOGGER = LoggerFactory.getLogger(MyTask.class);

    public static String formatDate(Date d) {
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        return sdf.format(d);
    }


    private static ScheduledExecutorService excutor = Executors.newSingleThreadScheduledExecutor();

    /**
     * 按指定频率周期执行某个任务 <br>
     * 初始化延迟0ms开始执行，每隔5ms重新执行一次任务。
     *
     * @param runnable //执行线程
     * @param time     //当前系统时间
     */
    public void fixedRate(String time, Runnable runnable) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        long oneDay =   30 * 60 * 1000L;
        long initDelay = getTimeMillis(time) - System.currentTimeMillis();
        initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
        executor.scheduleAtFixedRate(runnable, //执行线程
                initDelay,  //初始化延迟
                oneDay, //两次开始的执行的最小时间间隔
                TimeUnit.MILLISECONDS //计时单位
        );
    }

    /**
     * 每天凌晨1点执行一次
     */
    public void dayOfDelay(String time, Runnable command) {
        ScheduledExecutorService executor = Executors.newScheduledThreadPool(1);
        long oneDay = 24 * 60 * 60 * 1000L;
        long initDelay = getTimeMillis(time) - System.currentTimeMillis();
        initDelay = initDelay > 0 ? initDelay : oneDay + initDelay;
        executor.scheduleAtFixedRate(command, initDelay, oneDay, TimeUnit.MILLISECONDS);
    }

    /**
     * 获取给定时间对应的毫秒数
     *
     * @param time "HH:mm:ss"
     * @return
     */
    private static long getTimeMillis(String time) {
        try {
            DateFormat dateFormat = new SimpleDateFormat("yy-MM-dd HH:mm:ss");
            Date currentDate = dateFormat.parse(formatDate(new Date()) + " " + time);
            return currentDate.getTime();
        } catch (ParseException e) {
            LOGGER.error("异常信息=====");
        }
        return 0;
    }


    public static void main(String[] args) {
        MyTask myTask = new MyTask();
        String time = "15:50:00";
        //System.out.println(time);
        /*myTask.fixedRate(time, new ReadFileFromFTPTask());*/
    }

}
